/**
 * Layui 及 jquery 工具类
 */
window.LayuiJqUtil = function (){
	
	/**
	 * 获取url中的参数
	 * @param {Object} name
	 */
	var getUrlParamVal = function (name) {
	    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
	    if (r != null) {return unescape(r[2]) ;}else {return null;}  //返回参数值
	}

	/**
	 * 获取页面请求参数并返回对象.
	 * @returns {Object}
	 */
	var getUrlParamObj = function () {
		var url = window.location.href; //获取url中"?"符后的字串 
		var theRequest = new Object();
		var index = url.indexOf("?");
		var str = null;
		var strs = null;
		
		if(index != -1 || ((index = url.indexOf("#")) && index != -1)) {
			str = url.substr(index + 1); 
		  	strs = str.split("&");
			var entry = null;
		  	for(var i = 0; i < strs.length; i ++) {
				entry = strs[i].split("=");
		  		theRequest[entry[0]]=decodeURIComponent(entry[1]);
		  	}
		}
		return theRequest; 
	}

	/**
	 * 时间格式化.
	 * @param dateObj 时间对象. 
	 * @param format 格式化模板.
	 * @returns
	 */
	var formateDate = function (dateObj , format)
	{
		if(dateObj instanceof Date ){
			
		}else if ( !isNaN(dateObj) ){
			dateObj = new Date(parseInt(dateObj));
		}else{
			return "" ;
		}
		var o = {
		"M+" : dateObj.getMonth()+1, //month
		"d+" : dateObj.getDate(), //day
		"H+" : dateObj.getHours(), //hour of day 
		"m+" : dateObj.getMinutes(), //minute
		"s+" : dateObj.getSeconds(), //second
		"q+" : Math.floor((dateObj.getMonth()+3)/3), //quarter
		"S" : dateObj.getMilliseconds() //millisecond
		}
		if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
		(dateObj.getFullYear()+"").substr(4- RegExp.$1.length));
		for(var k in o)if(new RegExp("("+ k +")").test(format))
		format = format.replace(RegExp.$1,
		RegExp.$1.length==1? o[k] :
		("00"+ o[k]).substr((""+ o[k]).length));
		return format;
	}

	/**
	 * 获取表单
	 * jqFormObj : 表单的jQuery对象
	 */
	var jqGetFormDataObj = function(jqFormObj){
		var formData = {};
		var formDataArray = jqFormObj.serializeArray();
		// console.info(formDataArray);
		for(var index in formDataArray){
			tmpData = formDataArray[index];
			if(tmpData.value && tmpData.value.length > 0 ){
				formData[tmpData.name]=tmpData.value;
			}
		}
		return formData ;
	}

	/**
	 * layer 打开选择窗口
	 * @param {Object} inOptions
	 */
	var layerOpenChooseWin = function(inOptions){

		var options = {
			 url:"" 
			,title:"窗口" 
			,width: 600
			,height: 500
			,subEleId : ""
			,subEleVal: ""
			,fedback : function(){}
		};

		for(var idx in inOptions){
			var val = inOptions[idx];
			if(val){
				options[idx] = val;
			}
		}

		var winUrl = options.url ;
		var openTitle = options.title ;
		var w = options.width ;
		var h = options.height ;

		var randId = new Date().getTime(); 
	 	var tmpIptEleId = "chooseWinIpt" + randId ; 

 		var plusParam = "";
 		if(winUrl.indexOf("?") > 0 ){
 			plusParam = "&wintran_eleid=" + tmpIptEleId ;
 		}else{
 			plusParam = "?wintran_eleid=" + tmpIptEleId ;
 		}
 		var openUrl = winUrl + plusParam ;

		// 当前窗口创建临时(input)标签
		$("body").append('<input id="'+tmpIptEleId+'" type="hidden"  value=""  />')
		var tmpele = $(("#"+tmpIptEleId));
		tmpele.on("click",function(){
			var value = $(this).val();
			var jsonObj = JSON.parse(value);
			options.fedback(jsonObj);
			tmpele.remove();
		});

	 	layer.open({
			type: 2, // iframe窗口打开 
			area: [w + 'px', h + 'px'], // 窗口大小
			fix: false,  // 位置不固定
			maxmin: true, // 
			shadeClose: false, // 点击遮罩层触发关闭
			shade: 0.4, // 遮罩层透明度 
			title: openTitle, // 窗口标题 
			content: openUrl, // 打开地址 
			success: function(layerObj, index) {
				// 窗口打开成功处理 
				//向iframe页的元素传值  
				// var body = layer.getChildFrame('body', index);
				//向iframe页的id=house的元素传值  // 参考 https://yq.aliyun.com/ziliao/133150
				if(options.subEleId && options.subEleVal){
					try{
						var body = layer.getChildFrame('body', index);
						body.contents().find( ("#"+options.subEleId) ).val(options.subEleVal);
					}catch(e){
						console.error(e)
						layer.msg("子窗口赋值异常");
					}
				}
			},
			error: function(layero, index) {
				layer.alert("窗口打开异常");
			}
		});
 	}
	
	/**
	 * 窗口初始化并返回初始化值.
	 * @param {Object} inoptions
	 */
	function layerChooseWinInit(inoptions){
		var options={
			paramName_wintran_eleid : "wintran_eleid" , 
		}
		var parentIptEleId = null ; // 父窗口input标签的id
		var windName = window.name ; // 窗口名称
		var parentLayer = null ; // 父窗口的layer对象
		var windIndex = null ; //获取窗口索引
		var parentIptEle = null ; // 父窗口input标签
		parentIptEleId = getUrlParamVal(options.paramName_wintran_eleid); // 父窗口input标签的id
		if(parentIptEleId){
			parentIptEle = parent.document.getElementById(parentIptEleId); // 父窗口input标签
			parentLayer = parent.layer ; // 父窗口的layer对象
			if(parentLayer){
				windIndex = parentLayer.getFrameIndex(windName); //获取窗口索引
				if(windIndex){
					parentLayer.iframeAuto(windIndex); // 窗口自适应
					if(!parentIptEle){
						parentLayer.msg("未找到父窗口关联元素",function(){
							try{
								parentLayer.close(windIndex);
							}catch(e){
								console.error(e);
								// parentLayer.msg("窗口关闭异常");
							}
						})
					}else{
						// 父窗口元素设空值.
						parentIptEle.setAttribute("value","");
					}
				}
			}
		}

		var rtData = {
			windName:windName, // 窗口名称 
			windIndex : windIndex, // 窗口index
			parentLayer:parentLayer, // 父窗口layer对象
			parentIptEle : parentIptEle  // 父窗口input元素对象 
		};
		console.debug(rtData);
		return rtData ;
	}
	
	/**
	 * 关闭选择窗口,返回数据并关闭窗口
	 * @param {Object} rspData 返回数据 
	 * @param {Object} parentIptEle 父录入数据元素(dom)
	 * @param {Object} winFrameIndex 当前窗口的 iframeIndex
	 */
	var layerChooseWinRtdataAndClose = function(rspData,layerWinInitData ){
		
		if(!rspData){
			rspData = {};
		}
		var jsnStr = JSON.stringify(rspData) ;
		
		var parentIptEle = layerWinInitData.parentIptEle;
		var winFrameIndex = layerWinInitData.windIndex ;
		// console.debug("窗口提取的值="+jsnStr);
		if(parentIptEle){
			// 赋值
			try{
				parentIptEle.setAttribute("value",jsnStr) ;
				parentIptEle.click();
			}catch(e){
				console.error(e);
			}
		}
		// 关闭窗口
		layerWinInitData.parentLayer.close(winFrameIndex);
	}
	
	return {
		formateDate : formateDate ,
		getUrlParamVal : getUrlParamVal,
		getUrlParamObj : getUrlParamObj,
		jqGetFormDataObj:jqGetFormDataObj,
		layerOpenChooseWin : layerOpenChooseWin,
		layerChooseWinInit:layerChooseWinInit,
		layerChooseWinRtdataAndClose :layerChooseWinRtdataAndClose ,
		dft:null
	}
}


